package controllers

import (
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/microcosm-cc/bluemonday"
	"github.com/russross/blackfriday"
	"math"
	"net/http"
	"strconv"
	"test/helpers"
	"test/models"
	"test/system"
)

//test
func IndexTest(c *gin.Context) {

	user,_ := c.Get(CONTEXT_USER_KEY)
	//fmt.Println(user)


	if user != nil {
		u, ok := user.(models.User)
		fmt.Println(u.ID)
		fmt.Println(ok)
	}



}

func IndexJson(c *gin.Context) {

	res := helpers.Md5("wubuze@qq.com123456")
	c.JSON(200, res)
}

//首页
func IndexGet(c *gin.Context) {

	var (
		page      string
		pageIndex int
		pageSize  = system.GetConfiguration().PageSize
		posts     []*models.Post
		err       error
		total     int
		policy    *bluemonday.Policy
	)
	page = c.Query("page")
	page2 := c.Param("page")
	fmt.Println(page)
	fmt.Println(page2)

	pageIndex, _ = strconv.Atoi(page)
	if pageIndex <= 0 {
		pageIndex = 1
	}

	posts, err = models.ListPublishedPost("", pageIndex, pageSize)

	//fmt.Print("posts ")
	//fmt.Print(posts)

	if err != nil {
		println("error")
		return
	}
	total, err = models.CountPostByTag("")
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	session := sessions.Default(c)
	user := session.Get(SESSION_KEY)

	policy = bluemonday.StrictPolicy()
	for _, post := range posts {
		post.Tags, _ = models.ListTagByPostId(strconv.FormatUint(uint64(post.ID), 10))
		post.Body = policy.Sanitize(string(blackfriday.MarkdownCommon([]byte(post.Body))))
	}

	c.HTML(http.StatusOK, "index/index.html", gin.H{
		"posts":     posts,
		"tags":      models.MustListTag(),
		"totalPage": int(math.Ceil(float64(total) / float64(pageSize))),
		"pageIndex": pageIndex,
		"user":      user,
		"path":            c.Request.URL.Path,
		"maxReadPosts":    models.MustListMaxReadPost(),
	})

}

func Home(c *gin.Context) {
	c.HTML(http.StatusOK, "index/welcome.html", gin.H{
		"title": "Welcome GO GIN",
	})
}

func AdminIndex(c *gin.Context) {
	user, _ := c.Get(CONTEXT_USER_KEY)

	fmt.Println(user)
	c.HTML(http.StatusOK, "admin/index.html", gin.H{
		"pageCount":    models.CountPage(),
		"postCount":    models.CountPost(),
		"tagCount":     models.CountTag(),
		"commentCount": models.CountComment(),
		"user":         user,
		"comments":     models.MustListUnreadComment(),
	})
}
